package com.tangyuan.common.exception;

import com.tangyuan.common.result.Result;
import com.tangyuan.common.result.ResultCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;


@ControllerAdvice
@Slf4j
public class ExceptionHandlerInterceptor {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public Result<String> validExceptionHandler(MethodArgumentNotValidException exception) {

        // 获取异常信息
        String message = exception.getBindingResult().getFieldError().getDefaultMessage();

        // 返回前端
        Result result = new Result();
        result.setCode(400);
        result.setData("");
        result.setMessage(message);
        return result;
    }

    @ExceptionHandler(BindException.class)
    public ResponseEntity<Result> handleBindException(BindException ex) {
        Map<String, String> errors = new HashMap<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errors.put(fieldName, errorMessage);
        });


        return ResponseEntity.badRequest().body(Result.build(errors,ResultCodeEnum.ARGUMENT_VALID_ERROR));
    }

    @ExceptionHandler(HeadlinesException.class)
    @ResponseBody
    public Result handleHeadlinesException(HeadlinesException exception) {
        // 获取异常信息
        String message = exception.getMessage();
        Integer code = exception.getCode();
        log.error("打印百家捕获异常，发布百家小视频和文章接口，错误信息{}，错误码{}", message, code);
        // 返回前端
        Result result = new Result();
        result.setCode(code);
        result.setData("");
        result.setMessage(message);
        return result;
    }

    @ExceptionHandler(TangYuanException.class)
    @ResponseBody
    public Result handleTangYuanException(TangYuanException exception) {
        // 获取异常信息
        String message = exception.getMessage();
        Integer code = exception.getCode();
        log.error("打印唐园捕获异常，错误信息{}，错误码{}", message, code);
        // 返回前端
        Result result = new Result();
        result.setCode(code);
        result.setData("");
        result.setMessage(message);
        return result;
    }

}

